// atcoder 410 D
#include <bits/stdc++.h>
#define mp(a, b) make_pair(a, b)
using namespace std;

typedef long long ll;
typedef unsigned long long ull;
const int N = 1010;
int n, m, ans = INT_MAX;

vector<pair<int, int>> G[N];
bool vis[N][1 << 10];
int main() {

  cin >> n >> m;

  for (int i = 1; i <= m; i++) {
    int a, b, w;
    cin >> a >> b >> w;//起点 终点， 权重
    G[a].push_back({b, w});
    //G[b].push_back({a, w}); // 无向图
  }

  queue<pair<int, int>> q;
  vis[1][0] = true;
  q.push({1, 0});
  while (!q.empty()) {
    int u = q.front().first;
    int x = q.front().second;
    q.pop();
    for (auto son : G[u]) {
      int v = son.first;
      int w = son.second;
      int nx = x ^ w;
      if (!vis[v][nx]) {
        vis[v][nx] = true;
        q.push({v, nx});
      }
    }
  }
  for (int x = 0; x < N; x++) {
    if (vis[n][x]) {
      cout << x << '\n';
      return 0;
    }
  }
  cout << -1 << '\n';
  return 0;
}